package jnpf.permission.service.impl;


import cn.hutool.core.text.StrPool;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnpf.emnus.SearchMethodEnum;
import jnpf.base.UserInfo;
import jnpf.base.model.base.SystemBaeModel;
import jnpf.base.model.button.ButtonModel;
import jnpf.base.model.column.ColumnModel;
import jnpf.base.model.form.ModuleFormModel;
import jnpf.base.model.module.ModuleModel;
import jnpf.base.model.resource.ResourceModel;
import jnpf.base.service.SuperServiceImpl;
import jnpf.base.service.SystemService;
import jnpf.config.ConfigValueUtil;
import jnpf.database.model.dto.PrepSqlDTO;
import jnpf.database.sql.util.SqlFrameFastUtil;
import jnpf.database.util.DataSourceUtil;
import jnpf.database.util.DbTypeUtil;
import jnpf.database.util.JdbcUtil;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.permission.constant.AuthorizeConst;
import jnpf.permission.entity.AuthorizeEntity;
import jnpf.permission.entity.OrganizeAdministratorEntity;
import jnpf.permission.entity.RoleEntity;
import jnpf.permission.entity.UserRelationEntity;
import jnpf.permission.mapper.AuthorizeMapper;
import jnpf.permission.model.authorize.*;
import jnpf.permission.model.portalManage.AuthorizePortalManagePrimary;
import jnpf.permission.service.*;
import jnpf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.mybatis.dynamic.sql.*;
import org.mybatis.dynamic.sql.select.QueryExpressionDSL;
import org.mybatis.dynamic.sql.select.SelectModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 操作权限
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月26日 上午9:18
 */
@Slf4j
@Service
@DSTransactional
public class AuthorizeServiceImpl extends SuperServiceImpl<AuthorizeMapper, AuthorizeEntity> implements AuthorizeService {

    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private DataSourceUtil dataSourceUtils;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private CacheKeyUtil cacheKeyUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private OrganizeAdministratorService organizeAdminIsTratorService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private DataSource dataSource;

    @Override
    public AuthorizeVO getAuthorize(boolean isCache) {
        // 是否从缓冲里面获取权限
        if (isCache) {
            return getCacheAuthor(userProvider.get());
        } else {
            return getAuthorize(userProvider.get());
        }
    }

    private AuthorizeVO getCacheAuthor(UserInfo userInfo) {
        // 是否从缓冲里面获取权限
        String cacheKey = cacheKeyUtil.getUserAuthorize() + userInfo.getUserId();
        if (!redisUtil.exists(cacheKey)) {
            AuthorizeVO authorizeModel = getAuthorize(userInfo);
            if (authorizeModel.getModuleList().size() != 0) {
                redisUtil.insert(cacheKey, authorizeModel, 60);
            }
            return authorizeModel;
        } else {
            return JsonUtil.getJsonToBean(redisUtil.getString(cacheKey).toString(), AuthorizeVO.class);
        }
    }

    @Override
    public AuthorizeVO getAuthorize(UserInfo userInfo) {
        List<ModuleModel> moduleList = new ArrayList<>();
        List<ButtonModel> buttonList = new ArrayList<>();
        List<ColumnModel> columnList = new ArrayList<>();
        List<ResourceModel> resourceList = new ArrayList<>();
        List<ModuleFormModel> formsList = new ArrayList<>();
        List<SystemBaeModel> systemList = new ArrayList<>();
        Boolean isAdmin = userInfo.getIsAdministrator();
//        String majorOrgId = userService.getInfo(userInfo.getUserId()).getOrganizeId();
        if (!isAdmin) {
            List<String> roleIds = new ArrayList<>();
            roleService.getRoleIdsByCurrentUser(userInfo.getOrganizeId()).forEach(role -> {
                RoleEntity info = roleService.getInfo(role);
                //判断角色状态是否为有效，显示当前组织内角色的并集
                if (info != null && info.getEnabledMark() == 1) {
                    roleIds.add("'" + role + "'" );
                }
            });
            if (roleIds.size() != 0) {
                String roleIdsStr = String.join("," , roleIds);
                systemList = this.baseMapper.findSystem(roleIdsStr);
                moduleList = this.baseMapper.findModule(roleIdsStr);
                buttonList = this.baseMapper.findButton(roleIdsStr);
                columnList = this.baseMapper.findColumn(roleIdsStr);
                resourceList = this.baseMapper.findResource(roleIdsStr);
                formsList = this.baseMapper.findForms(roleIdsStr);
            }

        } else {
            moduleList = this.baseMapper.findModuleAdmin(1);
            buttonList = this.baseMapper.findButtonAdmin(1);
            columnList = this.baseMapper.findColumnAdmin(1);
            resourceList = this.baseMapper.findResourceAdmin(1);
            formsList = this.baseMapper.findFormsAdmin(1);
            systemList = JsonUtil.getJsonToList(systemService.getList(null, true), SystemBaeModel.class);
        }
        return new AuthorizeVO(moduleList, buttonList, columnList, resourceList, formsList, systemList);
    }

    @Override
    public void savePortalManage(String portalManageId, SaveAuthForm saveAuthForm) {
        final String AUTHORIZE_PORTAL_MANAGE = "portalManage";
        final String AUTHORIZE_ROLE = "role";
        String userId = UserProvider.getLoginUserId();
        // 原始授权角色
        List<AuthorizeEntity> list = new ArrayList<>();
        for (int i = 0; i < saveAuthForm.getObjectId().length; i++) {
            AuthorizeEntity authorizeEntity = new AuthorizeEntity();
            authorizeEntity.setId(RandomUtil.uuId());
            authorizeEntity.setItemType(AUTHORIZE_PORTAL_MANAGE);
            authorizeEntity.setItemId(portalManageId);
            authorizeEntity.setObjectType(AUTHORIZE_ROLE);
            authorizeEntity.setObjectId(saveAuthForm.getObjectId()[i]);
            authorizeEntity.setSortCode((long) i);
            authorizeEntity.setCreatorTime(new Date());
            authorizeEntity.setCreatorUserId(userId);
            list.add(authorizeEntity);
        }
        remove(new AuthorizePortalManagePrimary(null, portalManageId).getQuery());
        saveBatch(list);
    }

    @Override
    public void save(String objectId, AuthorizeDataUpForm authorizeList) {
        SaveBatchForm form = JsonUtil.getJsonToBean(authorizeList, SaveBatchForm.class);
        form.setRoleIds(new String[]{objectId});
        this.saveBatch(form, false);
    }

    @Override
    public void saveBatch(SaveBatchForm saveBatchForm, boolean isBatch) {
        try {
            UserInfo userInfo = userProvider.get();

            List<AuthorizeEntity> objectList = new ArrayList<>();
            List<AuthorizeEntity> authorizeList = new ArrayList<>();
            // 设置权限归属对象
            setEntity(saveBatchForm.getUserIds(), AuthorizeConst.USER, objectList, true);
            setEntity(saveBatchForm.getPositionIds(), AuthorizeConst.POSITION, objectList, true);
            setEntity(saveBatchForm.getRoleIds(), AuthorizeConst.ROLE, objectList, true);
//            setEntity(saveBatchForm.getSystemIds(), AuthorizeConst.SYSTEM, objectList, true);
            // 设置权限模块
            setEntity(saveBatchForm.getButton(), AuthorizeConst.BUTTON, authorizeList, false);
            setEntity(saveBatchForm.getModule(), AuthorizeConst.MODULE, authorizeList, false);
            setEntity(saveBatchForm.getColumn(), AuthorizeConst.COLUMN, authorizeList, false);
            setEntity(saveBatchForm.getResource(), AuthorizeConst.RESOURCE, authorizeList, false);
            setEntity(saveBatchForm.getForm(), AuthorizeConst.FROM, authorizeList, false);
            setEntity(saveBatchForm.getSystemIds(), AuthorizeConst.SYSTEM, authorizeList, false);

            // 删除角色相关信息
            List<String> objectIdAll = objectList.stream().map(AuthorizeEntity::getObjectId).collect(Collectors.toList());
            userService.delCurRoleUser(objectIdAll);
            if (!isBatch) {
                String ids = String.join("," , objectIdAll);
                JdbcUtil.delete(new PrepSqlDTO(XSSEscape.escapeEmpty(SqlFrameFastUtil.AUTHOR_DEL.replace("{authorizeIds}" , ids))).withConn(dataSourceUtils, null));
            }

            // 插入数据
            String sql = DbTypeUtil.checkOracle(dataSourceUtils) || DbTypeUtil.checkPostgre(dataSourceUtils) ?
                    SqlFrameFastUtil.INSERT_AUTHORIZE2 : SqlFrameFastUtil.INSERT_AUTHORIZE;

            String column_key = StringUtil.EMPTY, column_plceholder = StringUtil.EMPTY, column_value = TenantDataSourceUtil.getTenantColumn();
            if (StringUtil.isNotEmpty(column_value)) {
                column_key = StrPool.COMMA + configValueUtil.getMultiTenantColumn();
                column_plceholder = ",?";
            }
            sql = sql.replace("%COLUMN_KEY%" , column_key).replace("%COLUMN_PLACEHOLDER%" , column_plceholder);
            for (int i = 0; i < objectList.size(); i++) {

                for (AuthorizeEntity entityItem : authorizeList) {
                    List<Object> data = new LinkedList<>();
                    data.add(RandomUtil.uuId());
                    data.add(entityItem.getItemType());
                    data.add(entityItem.getItemId());
                    data.add(objectList.get(i).getObjectType());
                    data.add(objectList.get(i).getObjectId());
                    data.add(i);
                    data.add(DateUtil.getNow());
                    data.add(userInfo.getUserId());
                    if (StringUtil.isNotEmpty(column_value)) {
                        data.add(column_value);
                    }
                    PrepSqlDTO dto = new PrepSqlDTO(sql, data).withConn(dataSourceUtils, null);
                    JdbcUtil.creUpDe(dto);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("权限报错:" + e.getMessage());
        }
    }

    /**
     * 权限
     */
    private void setEntity(String[] ids, String type, List<AuthorizeEntity> entityList, Boolean objectFlag) {
        if (ids != null) {
            for (String id : ids) {
                AuthorizeEntity entity = new AuthorizeEntity();
                if (objectFlag) {
                    entity.setObjectType(type);
                    entity.setObjectId(id);
                } else {
                    entity.setItemType(type);
                    entity.setItemId(id);
                }
                entityList.add(entity);
            }
        }
    }

    @Override
    public List<AuthorizeEntity> getListByUserId(boolean isAdmin, String userId) {
        if (!isAdmin) {
            QueryWrapper<UserRelationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(UserRelationEntity::getUserId, userId);
            List<UserRelationEntity> list = userRelationService.list(queryWrapper);
            List<String> userRelationList = list.stream().map(u -> u.getObjectId()).collect(Collectors.toList());
            userRelationList.add(userId);
            QueryWrapper<AuthorizeEntity> wrapper = new QueryWrapper<>();
            wrapper.lambda().in(AuthorizeEntity::getObjectId, userRelationList);
            return this.list(wrapper);
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public List<AuthorizeEntity> getListByObjectId(String objectId) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getObjectId, objectId);
        return this.list(queryWrapper);
    }

    @Override
    public Boolean existByObjId(String objectId) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getObjectId, objectId);
        queryWrapper.lambda().eq(AuthorizeEntity::getItemType, "module" );
        return this.count(queryWrapper) > 0;
    }

    @Override
    public List<SystemBaeModel> systemListByRoleIds(List<String> roleIds) {
        if (!userProvider.get().getIsAdministrator()) {
            StringJoiner joiner = new StringJoiner("," );
            if (roleIds.size() < 1) {
                roleIds.add("" );
            }
            roleIds.forEach(t -> joiner.add("'" + t + "'" ));
            List<SystemBaeModel> systemBaeModelList = this.baseMapper.findSystem(joiner.toString());
            return systemBaeModelList == null ? new ArrayList<>(16) : systemBaeModelList;
        }
        return JsonUtil.getJsonToList(systemService.getList(null, true), SystemBaeModel.class);
    }

    @Override
    public List<AuthorizeEntity> getListByObjectId(String objectId, String itemType) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getObjectId, objectId);
        queryWrapper.lambda().eq(AuthorizeEntity::getItemType, itemType);
        return this.list(queryWrapper);
    }

    @Override
    public List<AuthorizeEntity> getListByObjectAndItem(String itemId, String objectType) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getObjectType, objectType).eq(AuthorizeEntity::getItemId, itemId);
        return this.list(queryWrapper);
    }

    /**
     * 获取条件过滤
     *
     * @param conditionModel 数据权限条件模型
     * @return
     */
    @Override
    @DS("" )
    public <T> QueryWrapper<T> getCondition(AuthorizeConditionModel conditionModel) {
        QueryWrapper<T> queryWhere = conditionModel.getObj();
        String moduleId = conditionModel.getModuleId();
        String tableName = conditionModel.getTableName();
        UserInfo userInfo = userProvider.get();
        AuthorizeVO model = this.getAuthorize(true);
        List<ResourceModel> resourceList = model.getResourceList().stream().filter(m -> m.getModuleId().equals(moduleId)).collect(Collectors.toList());
        if (resourceList.size() == 0) {
            return null;
        }
        List<ResourceModel> resourceList1 = new ArrayList<>();
        //拼接计数
        int t = 1;
        for (ResourceModel item : resourceList) {
            if (item.getAllData() != null && item.getAllData() == 1) {
                t = 0;
                break;
            }
            List<ConditionModel> conditionModelList = JsonUtil.getJsonToList(item.getConditionJson(), ConditionModel.class);
            for (int i = 0; i < conditionModelList.size(); i++) {
                ConditionModel conditionItem = conditionModelList.get(i);
                for (int k = 0; k < conditionItem.getGroups().size(); k++) {
                    ConditionModel.ConditionItemModel fieldItem = conditionItem.getGroups().get(k);
                    String itemTable = fieldItem.getBindTable();
                    if (StringUtil.isNotEmpty(itemTable) && itemTable.equalsIgnoreCase(tableName)) {
                        resourceList1.add(item);
                    }
                }
            }
        }
        if (t == 1) {
            if (resourceList1.size() > 0) {
                queryWhere.and(tw -> {
                    for (ResourceModel item : resourceList1) {
                        List<ConditionModel> conditionModelList = JsonUtil.getJsonToList(item.getConditionJson(), ConditionModel.class);
                        for (int i = 0; i < conditionModelList.size(); i++) {
                            ConditionModel conditionItem = conditionModelList.get(i);
                            for (int k = 0; k < conditionItem.getGroups().size(); k++) {
                                ConditionModel.ConditionItemModel fieldItem = conditionItem.getGroups().get(k);
                                String itemField = fieldItem.getField();
                                String itemValue = fieldItem.getValue();
                                String itemMethod = fieldItem.getOp();
                                Object value;
                                if (AuthorizeConditionEnum.USER.getCondition().equals(itemValue)) { //当前用户
                                    value = userInfo.getUserId();
                                    //任意文本 当前用户 当前组织 包含为模糊查询
                                    if (itemMethod.equals(SearchMethodEnum.Included.getMessage())) {
                                        itemMethod = SearchMethodEnum.Like.getMessage();
                                    }
                                    if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())) {
                                        itemMethod = SearchMethodEnum.NotLike.getMessage();
                                    }
                                } else if (AuthorizeConditionEnum.ORGANIZE.getCondition().equals(itemValue)) { //当前组织
                                    String orgId = userInfo.getOrganizeId();
                                    if (StringUtil.isNotEmpty(userInfo.getDepartmentId())) {
                                        orgId = userInfo.getDepartmentId();
                                    }
                                    if (itemMethod.equals(SearchMethodEnum.Included.getMessage())) {
                                        itemMethod = SearchMethodEnum.Like.getMessage();
                                    }
                                    if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())) {
                                        itemMethod = SearchMethodEnum.NotLike.getMessage();
                                    }
                                    value = orgId;
                                } else if (AuthorizeConditionEnum.ORGANIZEANDUNDER.getCondition().equals(itemValue)) { //组织及子组织
                                    String orgId = userInfo.getOrganizeId();
                                    if (StringUtil.isNotEmpty(userInfo.getDepartmentId())) {
                                        orgId = userInfo.getDepartmentId();
                                    }
                                    List<String> underOrganizations = organizeService.getUnderOrganizations(orgId);
                                    underOrganizations.add(orgId);
                                    value = underOrganizations;
                                } else if (AuthorizeConditionEnum.USERANDUNDER.getCondition().equals(itemValue)) { //用户及用户下属
                                    List<String> idsList = new ArrayList<>();
                                    if (userInfo.getSubordinateIds().size() > 0) {
                                        idsList = userInfo.getSubordinateIds();
                                    }
                                    idsList.add(userInfo.getUserId());
                                    value = idsList;
                                } else if (AuthorizeConditionEnum.BRANCHMANAGEORG.getCondition().equals(itemValue)) { //分管组织
                                    List<OrganizeAdministratorEntity> organizeAdministratorEntity = organizeAdminIsTratorService.getListByUserID(userInfo.getUserId());
                                    //子
                                    List<OrganizeAdministratorEntity> organizeAdministratorEntity1 = new ArrayList<>(organizeAdministratorEntity);
                                    //父
                                    List<OrganizeAdministratorEntity> organizeAdministratorEntity2 = new ArrayList<>(organizeAdministratorEntity);
                                    List<String> allIdList = new ArrayList<>();
                                    //子
                                    List<String> childList = organizeAdministratorEntity1.stream().filter(orgAdmin -> orgAdmin.getSubLayerSelect() == 1).map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());
                                    //父
                                    List<String> fathetList = organizeAdministratorEntity2.stream().filter(orgAdmin -> orgAdmin.getThisLayerSelect() == 1).map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());
                                    for (String org : childList) {
                                        List<String> underOrganizations = organizeService.getUnderOrganizations(org);
                                        if (underOrganizations.size() > 0) {
                                            allIdList.addAll(underOrganizations);
                                        }
                                    }
                                    if (fathetList.size() > 0) {
                                        allIdList.addAll(fathetList);
                                    }
                                    //空集合处理
                                    if (allIdList.size() == 0) {
                                        allIdList.add("jnpfNullList" );
                                    }
                                    value = allIdList;
                                } else if (AuthorizeConditionEnum.BRANCHMANAGEORGANIZEUNDER.getCondition().equals(itemValue)) { //分管组织及子组织
                                    List<OrganizeAdministratorEntity> organizeAdministratorEntity = organizeAdminIsTratorService.getListByUserID(userInfo.getUserId());

                                    List<OrganizeAdministratorEntity> organizeAdministratorEntity1 = new ArrayList<>(organizeAdministratorEntity);

                                    List<OrganizeAdministratorEntity> organizeAdministratorEntity2 = new ArrayList<>(organizeAdministratorEntity);

                                    List<String> allIdList = new ArrayList<>();
                                    //需要子集
                                    List<String> childList = new ArrayList<>();

                                    List<String> thisList = organizeAdministratorEntity1.stream().filter(orgAdmin -> orgAdmin.getThisLayerSelect() == 1)
                                            .map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());

                                    List<String> subList = organizeAdministratorEntity2.stream().filter(orgAdmin -> orgAdmin.getSubLayerSelect() == 1)
                                            .map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());

                                    if (thisList.size() > 0) {
                                        allIdList.addAll(thisList);
                                        childList.addAll(thisList);
                                    }
                                    if (subList.size() > 0) {
                                        childList.addAll(subList);
                                    }

                                    for (String orgID : childList) {
                                        List<String> underOrganizations = organizeService.getUnderOrganizations(orgID);
                                        if (underOrganizations.size() > 0) {
                                            allIdList.addAll(underOrganizations);
                                        }
                                    }
                                    if (allIdList.size() == 0) {
                                        allIdList.add("jnpfNullList" );
                                    }
                                    value = allIdList;
                                } else {//任意文本
                                    value = itemValue;
                                    if (itemMethod.equals(SearchMethodEnum.Included.getMessage())) {
                                        itemMethod = SearchMethodEnum.Like.getMessage();
                                    }
                                    if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())) {
                                        itemMethod = SearchMethodEnum.NotLike.getMessage();
                                    }
                                }
                                if ("and".equalsIgnoreCase(conditionItem.getLogic())) {
                                    if (itemMethod.equals(SearchMethodEnum.Equal.getMessage())) {
                                        tw.eq(itemField, value);
                                    } else if (itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())) {
                                        tw.ne(itemField, value);
                                    } else if (itemMethod.equals(SearchMethodEnum.LessThan.getMessage())) {
                                        tw.lt(itemField, value);
                                    } else if (itemMethod.equals(SearchMethodEnum.LessThanOrEqual.getMessage())) {
                                        tw.le(itemField, value);
                                    } else if (itemMethod.equals(SearchMethodEnum.GreaterThan.getMessage())) {
                                        tw.gt(itemField, value);
                                    } else if (itemMethod.equals(SearchMethodEnum.GreaterThanOrEqual.getMessage())) {
                                        tw.ge(itemField, value);
                                    } else if (itemMethod.equals(SearchMethodEnum.Included.getMessage())) {
                                        tw.in(itemField, (List) value);
                                    } else if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())) {
                                        tw.notIn(itemField, (List) value);
                                    } else if (itemMethod.equals(SearchMethodEnum.Like.getMessage())) {
                                        tw.like(itemField, value);
                                    } else if (itemMethod.equals(SearchMethodEnum.NotLike.getMessage())) {
                                        tw.notLike(itemField, value);
                                    }
                                } else {
                                    if (itemMethod.equals(SearchMethodEnum.Equal.getMessage())) {
                                        tw.or(
                                                qw -> qw.eq(itemField, value)
                                        );
                                    } else if (itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())) {
                                        tw.or(
                                                qw -> qw.ne(itemField, value)
                                        );
                                    } else if (itemMethod.equals(SearchMethodEnum.LessThan.getMessage())) {
                                        tw.or(
                                                qw -> qw.lt(itemField, value)
                                        );
                                    } else if (itemMethod.equals(SearchMethodEnum.LessThanOrEqual.getMessage())) {
                                        tw.or(
                                                qw -> qw.le(itemField, value)
                                        );
                                    } else if (itemMethod.equals(SearchMethodEnum.GreaterThan.getMessage())) {
                                        tw.or(
                                                qw -> qw.gt(itemField, value)
                                        );
                                    } else if (itemMethod.equals(SearchMethodEnum.GreaterThanOrEqual.getMessage())) {
                                        tw.or(
                                                qw -> qw.ge(itemField, value)
                                        );
                                    } else if (itemMethod.equals(SearchMethodEnum.Included.getMessage())) {
                                        tw.or(
                                                qw -> qw.in(itemField, (List) value)
                                        );
                                    } else if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())) {
                                        tw.or(
                                                qw -> qw.notIn(itemField, (List) value)
                                        );
                                    } else if (itemMethod.equals(SearchMethodEnum.Like.getMessage())) {
                                        tw.or(
                                                qw -> qw.like(itemField, value)
                                        );
                                    } else if (itemMethod.equals(SearchMethodEnum.NotLike.getMessage())) {
                                        tw.or(
                                                qw -> qw.notLike(itemField, value)
                                        );
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }
        return queryWhere;
    }


    /**
     * 获取条件过滤
     *
     * @param userInfo  用户信息
     * @param moduleId  功能模块Id
     * @param tableName 主表名
     * @return 是否分配方案
     */
    @Override
    @DS("" )
    public boolean getConditionSql(UserInfo userInfo, String moduleId, String tableName, QueryExpressionDSL<SelectModel>.QueryExpressionWhereBuilder from, List<OnlineDynamicSqlModel> sqlModelList) {
        AuthorizeVO model = this.getAuthorize(true);
        List<ResourceModel> resourceList = model.getResourceList().stream().filter(m -> m.getModuleId().equals(moduleId)).collect(Collectors.toList());
        //未分配权限方案
        if (resourceList.size() == 0) {
            return false;
        }
        //先遍历一次 查找其中有没有全部方案
        long count = resourceList.stream().filter(item -> "jnpf_alldata".equals(item.getEnCode())).count();
        if (count > 0) {
            return true;
        }
        //方案
        for (ResourceModel item : resourceList) {
            List<ConditionModel> conditionModelList = JsonUtil.getJsonToList(item.getConditionJson(), ConditionModel.class);
            //分组
            List<AndOrCriteriaGroup> groupList = new ArrayList<>();
            SqlColumn<Object> firstColumn = null;
            VisitableCondition firstCondition = null;
            for (int i = 0; i < conditionModelList.size(); i++) {
                ConditionModel conditionItem = conditionModelList.get(i);

                //条件
                for (int k = 0; k < conditionItem.getGroups().size(); k++) {
                    ConditionModel.ConditionItemModel fieldItem = conditionItem.getGroups().get(k);
                    String itemField = fieldItem.getField();
                    if (tableName != null && !tableName.equals(fieldItem.getBindTable())) {
                        continue;
                    }
                    OnlineDynamicSqlModel onlineDynamicSqlModel = sqlModelList.stream().filter(sql -> sql.getTableName().equals(fieldItem.getBindTable())).findFirst().orElse(null);
                    SqlTable sqlTable = onlineDynamicSqlModel.getSqlTable();

					String itemValue = fieldItem.getValue();
					String itemMethod = fieldItem.getOp();
					SqlColumn<Object> column = sqlTable.column(itemField);
					VisitableCondition condition;
					//当前用户
					if (AuthorizeConditionEnum.USER.getCondition().equals(itemValue)) {
						if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())) {
							condition= SqlBuilder.isNotLike(userInfo.getUserId());
						} else if (itemMethod.equals(SearchMethodEnum.Included.getMessage())) {
							condition= SqlBuilder.isLike(userInfo.getUserId());
						} else if (itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())) {
							condition= SqlBuilder.isNotEqualTo(userInfo.getUserId());
						} else if (itemMethod.equals(SearchMethodEnum.IsNull.getMessage())) {
							condition= SqlBuilder.isNull();
						} else if (itemMethod.equals(SearchMethodEnum.IsNotNull.getMessage())) {
							condition= SqlBuilder.isNotNull();
						} else {
							condition= SqlBuilder.isEqualTo(userInfo.getUserId());
						}
					}
					//当前组织
					else if (AuthorizeConditionEnum.ORGANIZE.getCondition().equals(itemValue)) {
						String orgId = userInfo.getOrganizeId();
						if (StringUtil.isNotEmpty(userInfo.getDepartmentId())) {
							orgId = userInfo.getDepartmentId();
						}
						if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())) {
							condition= SqlBuilder.isNotLike(orgId);
						} else if (itemMethod.equals(SearchMethodEnum.Included.getMessage())) {
							condition= SqlBuilder.isLike(orgId);
						} else if (itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())) {
							condition= SqlBuilder.isNotEqualTo(orgId);
						} else if (itemMethod.equals(SearchMethodEnum.IsNull.getMessage())) {
							condition= SqlBuilder.isNull();
						} else if (itemMethod.equals(SearchMethodEnum.IsNotNull.getMessage())) {
							condition= SqlBuilder.isNotNull();
						} else {
							condition= SqlBuilder.isEqualTo(orgId);
						}
					}
					//当前组织及子组织
					else if (AuthorizeConditionEnum.ORGANIZEANDUNDER.getCondition().equals(itemValue)) {
						String orgId = userInfo.getOrganizeId();
						if (StringUtil.isNotEmpty(userInfo.getDepartmentId())) {
							orgId = userInfo.getDepartmentId();
						}
						//获取子组织
						List<String> underOrganizations = organizeService.getUnderOrganizations(orgId);
						underOrganizations.add(orgId);
						if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())){
							condition = SqlBuilder.isNotIn(underOrganizations);
						} else if (itemMethod.equals(SearchMethodEnum.IsNull.getMessage())) {
							condition= SqlBuilder.isNull();
						} else if (itemMethod.equals(SearchMethodEnum.IsNotNull.getMessage())) {
							condition= SqlBuilder.isNotNull();
						} else{
							condition = SqlBuilder.isIn(underOrganizations);
						}
					}
					//当前用户及下属
					else if (AuthorizeConditionEnum.USERANDUNDER.getCondition().equals(itemValue)) {
						List<String> subOrganizeIds = new ArrayList<>();
						if (userInfo.getSubordinateIds().size() > 0) {
							subOrganizeIds = userInfo.getSubordinateIds();
						}
						subOrganizeIds.add(userInfo.getUserId());
						if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())
								|| itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())){
							condition = SqlBuilder.isNotIn(subOrganizeIds);
						} else if (itemMethod.equals(SearchMethodEnum.IsNull.getMessage())) {
							condition= SqlBuilder.isNull();
						} else if (itemMethod.equals(SearchMethodEnum.IsNotNull.getMessage())) {
							condition= SqlBuilder.isNotNull();
						} else{
							condition = SqlBuilder.isIn(subOrganizeIds);
						}
					}
					//分管组织
					else if (AuthorizeConditionEnum.BRANCHMANAGEORG.getCondition().equals(itemValue)) {
						List<OrganizeAdministratorEntity> organizeAdministratorEntity = organizeAdminIsTratorService.getListByUserID(userInfo.getUserId());
						//子
						List<OrganizeAdministratorEntity> organizeAdministratorEntity1 = new ArrayList<>(organizeAdministratorEntity);
						//父
						List<OrganizeAdministratorEntity> organizeAdministratorEntity2 = new ArrayList<>(organizeAdministratorEntity);

                        List<String> allIdList = new ArrayList<>();

                        //子
                        List<String> childList = organizeAdministratorEntity1.stream().filter(orgAdmin -> orgAdmin.getSubLayerSelect() == 1).map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());
                        //父
                        List<String> fathetList = organizeAdministratorEntity2.stream().filter(orgAdmin -> orgAdmin.getThisLayerSelect() == 1).map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());

                        for (String org : childList) {
                            List<String> underOrganizations = organizeService.getUnderOrganizations(org);
                            if (underOrganizations.size() > 0) {
                                allIdList.addAll(underOrganizations);
                            }
                        }

						if (fathetList.size() > 0) {
							allIdList.addAll(fathetList);
						}
						String ids = allIdList.stream().map(id -> "?" ).collect(Collectors.joining("," ));
						if(CollectionUtils.sizeIsEmpty(allIdList))return false;
						if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())){
							condition = SqlBuilder.isNotIn(allIdList);
						} else if (itemMethod.equals(SearchMethodEnum.IsNull.getMessage())) {
							condition= SqlBuilder.isNull();
						} else if (itemMethod.equals(SearchMethodEnum.IsNotNull.getMessage())) {
							condition= SqlBuilder.isNotNull();
						} else{
							condition = SqlBuilder.isIn(allIdList);
						}
					}
					//分管组织及子组织
					else if (AuthorizeConditionEnum.BRANCHMANAGEORGANIZEUNDER.getCondition().equals(itemValue)) {
						List<OrganizeAdministratorEntity> organizeAdministratorEntity = organizeAdminIsTratorService.getListByUserID(userInfo.getUserId());

                        List<OrganizeAdministratorEntity> organizeAdministratorEntity1 = new ArrayList<>(organizeAdministratorEntity);

                        List<OrganizeAdministratorEntity> organizeAdministratorEntity2 = new ArrayList<>(organizeAdministratorEntity);

                        List<String> allIdList = new ArrayList<>();
                        //需要子集
                        List<String> childList = new ArrayList<>();

                        List<String> thisList = organizeAdministratorEntity1.stream().filter(orgAdmin -> orgAdmin.getThisLayerSelect() == 1)
                                .map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());

                        List<String> subList = organizeAdministratorEntity2.stream().filter(orgAdmin -> orgAdmin.getSubLayerSelect() == 1)
                                .map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());

                        if (thisList.size() > 0) {
                            allIdList.addAll(thisList);
                            childList.addAll(thisList);
                        }
                        if (subList.size() > 0) {
                            childList.addAll(subList);
                        }

						for (String orgID : childList) {
							List<String> underOrganizations = organizeService.getUnderOrganizations(orgID);
							if (underOrganizations.size() > 0) {
								allIdList.addAll(underOrganizations);
							}
						}
						if(CollectionUtils.sizeIsEmpty(allIdList))return false;
						List<String> orgAndSub = allIdList.stream().distinct().collect(Collectors.toList());
						if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())){
							condition = SqlBuilder.isNotIn(orgAndSub);
						} else if (itemMethod.equals(SearchMethodEnum.IsNull.getMessage())) {
							condition= SqlBuilder.isNull();
						} else if (itemMethod.equals(SearchMethodEnum.IsNotNull.getMessage())) {
							condition= SqlBuilder.isNotNull();
						} else{
							condition = SqlBuilder.isIn(orgAndSub);
						}
					}
					//任意文本
					else {
						if (itemMethod.equals(SearchMethodEnum.Equal.getMessage())) {
							condition= SqlBuilder.isEqualTo(itemValue);
						} else if (itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())) {
							condition= SqlBuilder.isNotEqualTo(itemValue);
						} else if (itemMethod.equals(SearchMethodEnum.LessThan.getMessage())) {
							condition= SqlBuilder.isLessThan(itemValue);
						} else if (itemMethod.equals(SearchMethodEnum.LessThanOrEqual.getMessage())) {
							condition= SqlBuilder.isLessThanOrEqualTo(itemValue);
						} else if (itemMethod.equals(SearchMethodEnum.GreaterThan.getMessage())) {
							condition= SqlBuilder.isGreaterThan(itemValue);
						} else if (itemMethod.equals(SearchMethodEnum.GreaterThanOrEqual.getMessage())) {
							condition= SqlBuilder.isGreaterThanOrEqualTo(itemValue);
						} else if (itemMethod.equals(SearchMethodEnum.IsNull.getMessage())) {
							condition= SqlBuilder.isNull();
						} else if (itemMethod.equals(SearchMethodEnum.IsNotNull.getMessage())) {
							condition= SqlBuilder.isNotNull();
						} else {
							condition = SqlBuilder.isEqualTo(itemValue);
						}
						if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())){
							itemValue = "%" + itemValue + "%";
							condition= SqlBuilder.isNotLike(itemValue);
						}
						if (itemMethod.equals(SearchMethodEnum.Included.getMessage())) {
							itemValue = "%" + itemValue + "%";
							condition= SqlBuilder.isLike(itemValue);
						}
					}
					if(firstColumn == null){
						firstColumn = column;
						firstCondition = condition;
					}else {
						if (conditionItem.getLogic().toLowerCase().equals("and")){
							groupList.add(SqlBuilder.and(column, condition));
						}else {
							groupList.add(SqlBuilder.or(column, condition));
						}
					}
				}
			}

            if (firstColumn != null) {
                if (groupList.size() > 0) {
                    from.and(firstColumn, firstCondition, groupList);
                } else {
                    from.and(firstColumn, firstCondition);
                }
            }
        }
        return true;
    }

    @Override
    public List<SystemBaeModel> findSystem(List<String> roleIds) {
        if (!userProvider.get().getIsAdministrator()) {
            StringJoiner joiner = new StringJoiner("," );
            if (roleIds.size() < 1) {
                roleIds.add("" );
            }
            roleIds.forEach(t -> joiner.add("'" + t + "'" ));
            List<SystemBaeModel> systemBaeModelList = this.baseMapper.findSystem(joiner.toString());
            return systemBaeModelList == null ? new ArrayList<>(16) : systemBaeModelList;
        }
        return JsonUtil.getJsonToList(systemService.getList(null, true), SystemBaeModel.class);
    }

}
